/*--------------------------------------------------------------------------------------------------- */
/* START Define 																					  */
/* Author: NGUYENNV										                                              */
/*----------------------------------------------------------------------------------------------------*/
var dialog;
var DIALOG_IS_SHOW = false;
var SELECTED_LAYER_NAME;  						/* Name of selected layer in combobox       		  */
var DISPLAY_LAYER_NAME ="";
var ID_LAYER;     								/* ID of selected layer 							  */
var ID_LAYER_OLD = 0;
var LAYER_LENGTH ;								/* length of layer that displayed on popup  		  */
var LAYER_LENGTH_OLD = 0;


var ARR_FIELD_ALIAS = new Array();				/* List of fields that is read from XML file		  */
var ARR_SELECTED_ITEM;							/* This array store list of id features were selected */
var COUNT_SELECTED_ITEM;
var TYPE_OF_SORT_FIELD =	"";                 /* Type of field ( int or text...)					  */
var SORT_BY_FIELD =	"";                         /* Name of sort field 								  */
var ARR_LAYER ;
var ARR_RESULT_SEARCH ;							/* Array that contains result of searching			  */
var ARR_RESULT_DISPLAY ;						/* Array that contains list of record for displaying  */
var ARR_PAGING;	
var sURL_Field = document.getElementById('txtRequest').value + "/Config/alias.xml";
var OBJECT ; 
var IS_SEARCH = false;
var PAGE_NUM = 0;
var PAGE_LENGTH = 25;							/* Maximum num of record on a page					   */
								
var TABLE_SHOW;									/* Table contain list of record						   */
var btnBack;  									/* Back button 										   */
var btnNxt;   									/* Next button 										   */
var CURRENT_PAGE = 1;
/*-----------------------------------------------------------------------------------------------------*/
/* END Define																						   */
/*-----------------------------------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------------------------*/
/* START OnLoad Read XML file							 											   */
/* Author: NGUYENNV										 											   */
/*-----------------------------------------------------------------------------------------------------*/
$.get(sURL_Field, function (data) {
	
    $(data).find('alias').each(function () {
        var $elevationpoints = $(this);
        
        $elevationpoints.find('Field').each(function () {
            var $fieldAlias = $(this);
            var _Index = $fieldAlias.attr('Index');
            var _Name = $fieldAlias.attr('Name');
            var _Type = $fieldAlias.attr('Type');
            var _Alias = $fieldAlias.attr('Alias');
            var _IsShow = $fieldAlias.attr('IsShow');
            var _IsEditor = $fieldAlias.attr('IsEditor');
            var _layerName = $fieldAlias.attr('layerName');
            var _field_alias = new Field_Aliass.create(_Index, _Name, _Type, _Alias, _IsShow, _IsEditor, _layerName);
            ARR_FIELD_ALIAS[ARR_FIELD_ALIAS.length] = _field_alias;
            
        });	        
    });
    
});

/*------------------------------------------------------------------------------------------------------*/
/* END OnLoad 											   												*/
/* Author: NGUYENNV										   												*/
/* Description:			Object of each field   			   												*/
/*------------------------------------------------------------------------------------------------------*/

Field_Aliass =
{
    Index: 0,
    Name: "",
    Type: "",
    Alias: "",
    IsShow: false,
    IsEditor: false,
    LayerName: "",

    create: function () {
        var len = arguments.length;
        if (len > 0) this.Index = arguments[0];
        if (len > 1) this.Name = arguments[1];
        if (len > 2) this.Type = arguments[2];
        if (len > 3) this.Alias = arguments[3];
        if (len > 4) this.IsShow = arguments[4] == "0" ? false : true;
        if (len > 5) this.IsEditor = arguments[5] == "0" ? false : true;
        if (len > 6) this.LayerName = arguments[6];        
    }
};

/*------------------------------------------------------------------------------------------------------*/
/* Function: showPopup							   														*/
/* Author: NGUYENNV										   												*/
/* Description:	Display popup for opening table attributes        	    								*/
/*------------------------------------------------------------------------------------------------------*/
function showPopup(_url) { 

	if(ID_LAYER < map.layers.length && ID_LAYER > 0)
		{
	 		AUI().use('aui-dialog', 'aui-io', 'event', 'event-custom', function(A) {

		     dialog = new A.Dialog({
		            					title: DISPLAY_LAYER_NAME,
		            					centered: true,
		            					draggable: true,
		            					modal: true,
		            					height: 500,
		            					width: 800,
		            					scrollbars: true,
		            					bodyContent: '<button type="button" onclick="dialogId.close()" value="close"></button>'
		        					}).plug(A.Plugin.IO, {uri:_url}).render();
		        dialog.show();
		 	 });
		}
	
	} 
/*------------------------------------------------------------------------------------------------------*/
/* Function: ShowPopupContent							   												*/
/* Author: NGUYENNV										   												*/
/* Description:		Show content on popup        	    												*/
/*------------------------------------------------------------------------------------------------------*/
function ShowPopupContent(layerName)
{	
	TABLE_SHOW = document.getElementById('tblList');
	RowHeader = document.createElement('tr');
	
	cell0Header = document.createElement('th');
	cell0Header.innerText  = "";
	cell0Header.setAttribute("width","200px");
	RowHeader.appendChild(cell0Header);
	TABLE_SHOW.appendChild(RowHeader);
	for(var i=0; i < ARR_FIELD_ALIAS.length;i++ )
		{
			if(layerName == ARR_FIELD_ALIAS[i].LayerName && ARR_FIELD_ALIAS[i].IsShow == true)
			{
				
				cell1Header = document.createElement('th');
				cell1Header.setAttribute("align","center");
				cell1Header.innerText  = ARR_FIELD_ALIAS[i].Alias;
				cell1Header.setAttribute("width","200px");
				cell1Header.setAttribute("height","30px");
				cell1Header.setAttribute("onClick","sortArr(this)");
				RowHeader.appendChild(cell1Header);
			}
		}
	//----------------------------------------------------------------
	RowFiltor = document.createElement('tr');
	cellFiltor0 = document.createElement('th');
	inputFld = document.createElement('input');
	inputFld.type = "checkbox"; //input type = textfield
	inputFld.name = "AllChks";
	inputFld.setAttribute("onClick","checkAll()");
   	inputFld.id = "chkbox";//assign id to input field
   	cellFiltor0.appendChild(inputFld);
	cellFiltor0.setAttribute("height","30px");
	RowFiltor.appendChild(cellFiltor0);
	for(var j=0; j < ARR_FIELD_ALIAS.length;j++ )
		{
			if(layerName == ARR_FIELD_ALIAS[j].LayerName && ARR_FIELD_ALIAS[j].IsShow == true)
				{
				cellF=document.createElement('td');
				cellF.setAttribute("align","center");
				textF = document.createElement('input');
				textF.type = "text";
				
				textF.id = ARR_FIELD_ALIAS[j].Name;
				textF.setAttribute("onkeypress","getSearchString(this)");
				cellF.appendChild(textF);
				RowFiltor.appendChild(cellF);
				}
		}
	TABLE_SHOW.appendChild(RowFiltor);
	PAGE_NUM = 0;
	ARR_RESULT_DISPLAY = new Array();
	ARR_RESULT_DISPLAY = ARR_LAYER;
	
	pagingPopup(ARR_RESULT_DISPLAY,PAGE_NUM);
	
	//addRowToTable(TABLE_SHOW, ARR_RESULT_DISPLAY);
	//alert("IDLayer = "+ID_LAYER +"id map 1 = "+ map.layers[ID_LAYER].features[10].id);
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: getTextCombo							   													*/
/* Author: NGUYENNV										   												*/
/* Description:	Get IdLayer, LayerLength when selecting layer on dropdown								*/
/*------------------------------------------------------------------------------------------------------*/
function getTextCombo(indexLayer, str)
{
	ARR_SELECTED_ITEM = new Array();
	COUNT_SELECTED_ITEM = 0;
	SELECTED_LAYER_NAME = str;
	ID_LAYER = indexLayer;
	LAYER_LENGTH = map.layers[ID_LAYER].features.length;
	ARR_LAYER = new Array();
	convertToArr(map.layers[ID_LAYER],SELECTED_LAYER_NAME);
}
/*------------------------------------------------------------------------------------------------------*/
/* Funtion: sortByType									   												*/
/* Author: NGUYENNV										   												*/
/* Description:	Sort array by column name	          													*/
/*------------------------------------------------------------------------------------------------------*/
function sortByType(arrLayer,colName,type)
{
	
	if(type == "int")
		{
		arrLayer.sort
	    (
	        function (a, b) {
	            var x = a.attribute[colName] - b.attribute[colName];
	            return x;
	        });
		}
	else
	{
	arrLayer.sort(function(a, b)
			{
			 nameA = a.attribute[colName].toLowerCase();
			 nameB = b.attribute[colName].toLowerCase();
			 if (nameA < nameB)
				 {
				 return -1;
				 }
			 if (nameA > nameB)
				  return 1;
			 return 0;
			});
	}
	
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: fillToTable							   													*/
/* Author: NGUYENNV										   												*/
/* Description:		After sorting, fill sorted list to table          									*/
/*------------------------------------------------------------------------------------------------------*/

function fillToTable(arr)
{
	for(var i = 0;i < LAYER_LENGTH; i++)
		{
			 Row = document.getElementById(i);
			 var count = 1;
			 chk = Row.getElementsByTagName("itemChk");
			 chk.id = arr[i].attribute["fid"];
			for(var j = 0; j< ARR_FIELD_ALIAS.length; j++)
				{
				if(SELECTED_LAYER_NAME == ARR_FIELD_ALIAS[j].LayerName)
					{

					   att = ARR_FIELD_ALIAS[j].Name;
					   Cells = Row.getElementsByTagName("td");   
					   Cells[count].innerHTML  = arr[i].attribute[att];
					   count = count + 1;
					}
				}
		}
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: fillToTable 											 	  								*/
/* Author: NGUYENNV										   												*/
/* Description:		fill list of attribute to array  													*/
/*------------------------------------------------------------------------------------------------------*/


/*------------------------------------------------------------------------------------------------------*/
/* Function: convertToArr 											   									*/
/* Author: NGUYENNV										   												*/
/* Description:		Fill list of object to array ARR_LAYER 												*/
/*------------------------------------------------------------------------------------------------------*/
function convertToArr(_layer, _layerName)
{
	findObject(SELECTED_LAYER_NAME);
	for(var i = 0;i < LAYER_LENGTH; i++)
		{
		//var _object ;
		_object =  new  OBJECT.create(i, "a","a","a","a","a","a","a","a","a");
		for(var j = 0; j< ARR_FIELD_ALIAS.length; j++)
				{
				if(_layerName == ARR_FIELD_ALIAS[j].LayerName)
					{
					  var  att = ARR_FIELD_ALIAS[j].Name;
					  if(att == "fid")
					  _object.attribute[att] = _layer.features[i].fid;
					  else
						  {
						  str = _layer.features[i].attributes[att];
						  if(str == null)
							  {
							  	str = "";
							  }
						  _object.attribute[att] = str;
						  }
					 
					}
				}
		 ARR_LAYER[i] = _object;
		
		}
	//alert("ID ARR = " +_layer.features[10].id);
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: findObject 											   									*/
/* Author: NGUYENNV										   												*/
/* Description:		Finding selected layer and asign it for OBJECT  									*/
/*------------------------------------------------------------------------------------------------------*/
function findObject(layername)
{
	switch(layername)
	{
	case "committee":
		OBJECT = committee;
	  break;
	case "railways":
		OBJECT = railways;
	  break;
	case "elevationpoints":
		OBJECT = elevationpoints;
	  break;
	case "rivers_lake":
		OBJECT = rivers_lake;
	  break;
	case "DWA_DiemDauNoi":
		OBJECT = DWA_DiemDauNoi;
	  break;
	case "DWA_HoGa":
		OBJECT = DWA_HoGa;
	  break;
	default:
		alert("Value is null");
	}

}
/*------------------------------------------------------------------------------------------------------*/
/* Function: sortArr 											   										*/
/* Author: NGUYENNV										   												*/
/* Description: Sorting data table that is displaying on page		 									*/
/*------------------------------------------------------------------------------------------------------*/
function sortArr(element)
{
	//alert("Sorting");
	var _name = "";
	var i = 1;
	for(var j = 0; j< ARR_FIELD_ALIAS.length; j++)
	{
	if(SELECTED_LAYER_NAME == ARR_FIELD_ALIAS[j].LayerName && ARR_FIELD_ALIAS[j].IsShow == true)
		{
			if(i == element.cellIndex)
				{
				_name = ARR_FIELD_ALIAS[j].Name;
				}
		
			i = i + 1;
			
		}
	}
	SORT_BY_FIELD = _name;
	//alert(_name);
	if(SORT_BY_FIELD != "")
	TYPE_OF_SORT_FIELD = getTypeOfField(SORT_BY_FIELD);
	if(TYPE_OF_SORT_FIELD != "")
		{
		//convertToArr(map.layers[ID_LAYER],SELECTED_LAYER_NAME);
		ARR_RESULT_DISPLAY = new Array();
		
		if(IS_SEARCH == false )
			ARR_RESULT_DISPLAY = ARR_LAYER;
		else 
			ARR_RESULT_DISPLAY = ARR_RESULT_SEARCH;
		
		sortByType(ARR_RESULT_DISPLAY,SORT_BY_FIELD, TYPE_OF_SORT_FIELD);
		PAGE_NUM = 0;
		pagingPopup(ARR_RESULT_DISPLAY,PAGE_NUM);
		//fillToTable(_array);
		}
	
}
/*------------------------------------------------------------------------------------------------------*/
/* 			 											   												*/
/* Author: NGUYENNV										   												*/
/* Description:		Get type of colName for sorting        	    										*/
/*------------------------------------------------------------------------------------------------------*/
function getTypeOfField(colName)
{
	var type="";
	for(var j = 0; j< ARR_FIELD_ALIAS.length; j++)
	{
		if(SELECTED_LAYER_NAME == ARR_FIELD_ALIAS[j].LayerName)
		{
			if(colName ==  ARR_FIELD_ALIAS[j].Name)
				{
					type = ARR_FIELD_ALIAS[j].Type;
				}
		}
	}
	return type;
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: getSearchString	 											   							*/
/* Author: NGUYENNV										   												*/
/* Description:		Get list of searching result and fill to popup          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function getSearchString(element)
{
	var _ID="";
	var _str="";
	var charCode = keycode = window.event.keyCode ;
	IS_SEARCH = true;
	_ID = element.id;
	if(charCode == 13)
		{
			for(var j = 0; j< ARR_FIELD_ALIAS.length; j++)
			{
				if(SELECTED_LAYER_NAME == ARR_FIELD_ALIAS[j].LayerName && ARR_FIELD_ALIAS[j].IsShow == true)
				{
					if(_ID ==  ARR_FIELD_ALIAS[j].Name)
					{
						_str = document.getElementById(_ID);
						 searchString(_ID, _str.value);
					}
				}
			}
		}
	//if(_str != "")
		
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: searchString	 												   							*/
/* Author: NGUYENNV										   												*/
/* Description:		Searching in a list of array                 	          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function searchString(colName, str)
{
	ARR_RESULT_SEARCH = new Array();
	//alert("length = "+LAYER_LENGTH);
	var count = 0;
	for(var i=0; i < LAYER_LENGTH ;i++ )
	{
		_str = ARR_LAYER[i].attribute[colName];
		if(_str != null)
			{
			//alert(i+" String  = "+_str);
			var re = new RegExp(str,"gi");
			if(_str.match(re) != null)
				{
					ARR_RESULT_SEARCH[count] = ARR_LAYER[i];
					count ++;
					//alert("count = " + count);
				}
			}
		//else alert("data is null");
	}
	ARR_RESULT_DISPLAY = new Array();
	ARR_RESULT_DISPLAY = ARR_RESULT_SEARCH;
	pagingPopup(ARR_RESULT_DISPLAY,PAGE_NUM);
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: clearTable	 													   							*/
/* Author: NGUYENNV										   												*/
/* Description:		Clear all row on table		                	          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function clearTable()
{
	var rowLength = document.getElementById("tblList").rows.length;
	
	for(var i = rowLength; i > 2;i--)
	{
		document.getElementById("tblList").deleteRow(i -1);
	}
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: addRowToTable	 	    										   							*/
/* Author: NGUYENNV										   												*/
/* Description:		Add rows to table 			                	          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function addRowToTable(table, _array)
{
	for(var i=0; i < _array.length ;i++ )
	{
		_check = false;
		_value = _array[i].attribute["fid"];
		if(makeCheckingItem(ARR_SELECTED_ITEM ,_value)==true)
			_check = true;
		//alert(_array[i].attribute["fid"] +" ARR_SELECTED_ITEM="+ARR_SELECTED_ITEM[i]);
    	row=document.createElement('tr');
    	row.id = i;
    	if(i%2 == 0) row.setAttribute("style","background-color: #AFEEEE");
  		 // cell 0-Checkbox Cell---------------------------------------------------
    		cell0=document.createElement('td');
    		cell0.setAttribute("height","20px");
    		 var inputFld = document.createElement('input');
    	    	 inputFld.type = "checkbox"; //input type = textfield
    	    	 inputFld.setAttribute("onClick","checkThisItem(this)");
    	    	 inputFld.checked = _check;
    	    	 inputFld.name = "itemChk";
    	       	 inputFld.id = i;//assign id to input field
    	     	// inputFld.value = strId;
    	     	 cell0.appendChild(inputFld);
    	     	 row.appendChild(cell0);
    	 // END cell 0-------------------------------------------------------------
    	     	for(var j=0; j < ARR_FIELD_ALIAS.length;j++ )
    	     		{
    	     			if(SELECTED_LAYER_NAME == ARR_FIELD_ALIAS[j].LayerName && ARR_FIELD_ALIAS[j].IsShow == true)
    	     				{
    	     					att = ARR_FIELD_ALIAS[j].Name;
    	     					cell=document.createElement('td');
    	     					cell.setAttribute("align","center");
    	     					//cell.setAttribute("height","40px");
    	     					field = _array[i].attribute[att];       	        		 		
    	     					cell.appendChild(document.createTextNode(field));        	        		 		
    	     					row.appendChild(cell);
    	     				}
    	     		}
    	     	table.appendChild(row);
	}
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: pagingPopup	 												   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Paging												          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function pagingPopup(_array,count)
{
	value = 1;
	length = _array.length;
	noOfPage = length/PAGE_LENGTH;
	ARR_PAGING = new Array();
	if(noOfPage%1 != 0)
		noOfPage = Math.floor(noOfPage)+1;
	if(count < noOfPage)
		CURRENT_PAGE = count + 1;
	
	length = length - PAGE_LENGTH * count;
	
		if(length >= PAGE_LENGTH)
		{
			for(var i= 0; i < PAGE_LENGTH; i++)
			{
			ARR_PAGING[i] = _array[PAGE_LENGTH * count + i];
			}
			value = 0;
		}
		else if(length >=0 && length < PAGE_LENGTH) 
		{
			for(var i= 0; i < length; i++)
			{
				ARR_PAGING[i] = _array[PAGE_LENGTH * count + i];
			}
			value = 0;
		}
		else value = 1;
		if(value == 0)
			{
			 clearTable();
			 addRowToTable(TABLE_SHOW, ARR_PAGING);
			 document.getElementById("IdlabTotal").innerText="Page "+ CURRENT_PAGE +" of " + noOfPage;
			}
		return value;
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: backPage	 													   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Paging when Back button is clicked					          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function backPage()
{
	btnBack = document.getElementById("btnBck");
	if(PAGE_NUM > 0)
	{
		
		PAGE_NUM --;
		if(pagingPopup(ARR_RESULT_DISPLAY,PAGE_NUM)==0)
		{
			btnNxt.disabled = false;
		}
	}
	else
		btnBack.disabled = true;
	
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: backPage	 													   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Paging when Next button is clicked					          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function nextPage()
{
	btnNxt = document.getElementById("btnNxt");
	PAGE_NUM ++;
	if(pagingPopup(ARR_RESULT_DISPLAY,PAGE_NUM)==0)
	{
		btnBack.disabled = false;
	}
	else
		{
			PAGE_NUM --;
			btnNxt.disabled = true;
		}
		
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: resetColorFeatures	 													   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Paging when Next button is clicked					          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function resetColorFeatures(_idLayer,_layerLength)
{
	for(var j=0; j < _layerLength;j++)
	map.layers[_idLayer].drawFeature(map.layers[_idLayer].features[j],"default");
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: checkThisItem 													   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Paging when Next button is clicked					          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function checkThisItem(element)
{
	_id = element.id;
	_value = ARR_PAGING[_id].attribute["fid"];
	
	if(element.checked == true)
		{
			ARR_SELECTED_ITEM[ARR_SELECTED_ITEM.length] = _value;
			//COUNT_SELECTED_ITEM++;
		}
	else
		{
			removeByValue(ARR_SELECTED_ITEM,_value);
			//COUNT_SELECTED_ITEM--;
		}
}
function checkAll()
{
	var inutTag = document.getElementsByName("itemChk");
	checkContrl = document.getElementById("chkbox");
	if(checkContrl.checked == true)
		{
			for(var i=0; i < ARR_PAGING.length; i++)
			{
				if(inutTag[i].type=='checkbox' && inutTag[i].checked==false)
					{
						inutTag[i].checked = true;
						_value = ARR_PAGING[i].attribute["fid"];
						insertToArr(ARR_SELECTED_ITEM,_value);
					}
			}
			
		}
	else
		for(var i=0; i < ARR_PAGING.length; i++)
		{
			inutTag[i].checked = false;
			_value = ARR_PAGING[i].attribute["fid"];
			removeByValue(ARR_SELECTED_ITEM, _value);
		}
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: removeByValue	 												   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Remove an element out of array						          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function removeByValue(arr, val) {
	for(var i=0; i<arr.length; i++) {
		if(arr[i] == val) {
			arr.splice(i, 1);
			break;
		}
	}
}

/*------------------------------------------------------------------------------------------------------*/
/* Function: makeCheckingItem												   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Checking this array contain the values 				          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function makeCheckingItem(_array, values_)
{
	for(var i=0; i <_array.length ; i++)
		{
			if(_array[i] == values_)
				return true;
		}
	return false;
	
}
/*------------------------------------------------------------------------------------------------------*/
/* Function: insertToArr													   							*/
/* Author: NGUYENNV										   												*/
/* Description:	Insert	 a value to array			 				          	    					*/
/*------------------------------------------------------------------------------------------------------*/
function insertToArr(_arrOut,_value)
{
		if(makeCheckingItem(_arrOut ,_value)==false)
			{
				
				_arrOut[_arrOut.length] = _value;
			}
}